<template>
  <div v-if="isinit" class="header-container">
    <div class="header-content">
      <!-- 欢迎信息 -->
      <div class="welcome-section">
        <span class="welcome-text">欢迎: {{ name }} ({{ username }})</span>
        <a
          href="https://kdocs.cn/l/cd8N1UTldHxy"
          target="_blank"
          class="feedback-link"
        >问题反馈</a>
      </div>

      <!-- 用户中心菜单 -->
      <el-menu
        class="user-menu"
        mode="horizontal"
        :default-active="activeIndex"
        :ellipsis="false"
        @select="handleSelect"
        background-color="#ffffff"
        text-color="#606266"
        active-text-color="#409EFF"
      >
        <el-sub-menu index="1">
          <template #title>
            <span>用户中心</span>
          </template>
          <el-menu-item index="1-1" @click="RePassword">修改密码</el-menu-item>
          <el-menu-item index="1-2" @click="ReUserInfo">修改用户信息</el-menu-item>
          <el-menu-item index="1-3" @click="LoginOut">退出登录</el-menu-item>
        </el-sub-menu>
      </el-menu>
    </div>
</div>
    <!-- 弹窗组件 -->
    <EditPassWord ref="re_password" />
    <EditUserInfo ref="re_user_info" />

</template>

<script setup>
import { ref, onMounted, watchEffect } from 'vue'
import { ElMessage } from 'element-plus'
import router from '@/router/index.js'
import setting from '@/setting.js'
import { jsonApi } from '@/global.js'
import EditPassWord from '@/components/Main/UserManger/EditPassWord.vue'
import EditUserInfo from '@/components/Main/UserManger/EditUserInfo.vue'

// 用户信息
const name = ref('')
const username = ref('')
const activeIndex = ref('1')

// 初始化状态
const isinit = ref(false)

// 获取用户信息
const getUserInfo = async () => {
  try {
    const response = await jsonApi('/user/info/')
    const data = await response.json()
    if (response.ok) {
      localStorage.setItem('userinfo', JSON.stringify(data))
      name.value = data.name
      username.value = data.username
    } else {
      ElMessage.error(`获取用户信息失败: ${data.detail}`)
    }
  } catch (e) {
    ElMessage.error(`获取用户信息失败: ${e}`)
  }
}

// 检查用户信息
const check_userinfo = () => {
  const storedUser = localStorage.getItem('userinfo')
  if (storedUser) {
    isinit.value = true
    const { name: n, username: u } = JSON.parse(storedUser)
    name.value = n
    username.value = u
  } else {
    getUserInfo().then(() => check_userinfo())
  }
}

// 获取所有用户信息（根据实际需求调整）
const getAllUser = async () => {
  try {
    const response = await jsonApi('/user/allinfo/', JSON.stringify({ name: '' }))
    const data = await response.json()
    localStorage.setItem('alluser', JSON.stringify(data))
  } catch (e) {
    ElMessage.error(`获取系统用户信息失败: ${e}`)
  }
}

// 初始化钩子
onMounted(() => {
  check_userinfo()
  getAllUser()
})

// 用户中心操作
const re_password = ref(null)
const re_user_info = ref(null)

const RePassword = () => {
  re_password.value?.open?.() || console.error('RePassword component not ready')
}

const ReUserInfo = () => {
  re_user_info.value?.open?.() || console.error('ReUserInfo component not ready')
}

const LoginOut = async () => {
  try {
    const jsonBody = { refresh: localStorage.getItem('refresh_token') }
    const response = await jsonApi('/user/logout/', JSON.stringify(jsonBody))
    if (response.ok) {
      ['access_token', 'refresh_token', 'user_groups', 'userinfo', 'reportinfo'].forEach(key => localStorage.removeItem(key))
      ElMessage.success('退出成功')
      await router.push('/login')
    }
  } catch (e) {
    ElMessage.error(`退出失败: ${e}`)
  }
}

// 菜单选择处理
const handleSelect = (key, keyPath) => {
  console.log('Menu selected:', key, keyPath)
}
</script>

<style scoped>
/* 容器优化 */
.header-container {
  background: linear-gradient(145deg, #f8fafc 0%, #f1f5f9 100%);
  border-bottom: 1px solid #e2e8f0;
  box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.05);
  position: relative;
  z-index: 1000;
  display: flex;
  flex-direction: column;
  gap: 0; /* 改为内部元素控制间距 */
}

/* 内容区域优化 */
.header-content {
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 64px; /* 固定高度避免影响外部布局 */
  margin: 0 24px; /* 改用 margin 控制左右间距 */
}

/* 欢迎信息优化 */
.welcome-section {
  display: flex;
  align-items: center;
  gap: 20px;
  padding: 8px 0; /* 在内部添加垂直 padding */
}

.welcome-text {
  font-size: 15px;
  color: #334155;
  font-weight: 600;
  letter-spacing: 0.5px;
  display: flex;
  align-items: center;
  gap: 8px;
}

.welcome-text::before {
  content: "👋";
  font-size: 18px;
}

.feedback-link {
  color: #3b82f6;
  text-decoration: none;
  font-size: 13px;
  font-weight: 500;
  padding: 6px 12px;
  border-radius: 6px;
  transition: all 0.2s cubic-bezier(0.4, 0, 0.2, 1);
  display: flex;
  align-items: center;
  gap: 6px;
}

.feedback-link:hover {
  background: #eff6ff;
  transform: translateY(-1px);
}

.feedback-link::before {
  content: "💬";
}

/* 用户菜单优化 */
.user-menu {
  background: rgba(255, 255, 255, 0.9);
  backdrop-filter: blur(4px);
  border-radius: 10px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  border: 1px solid #e2e8f0;
  padding: 0 12px;
}

:deep(.el-sub-menu__title) {
  height: 40px;
  line-height: 40px;
  padding: 0 20px !important;
  font-weight: 500;
  transition: all 0.2s ease;
}

:deep(.el-menu--horizontal) > .el-sub-menu:hover {
  background: rgba(241, 245, 249, 0.5);
}

:deep(.el-menu-item) {
  height: 36px;
  line-height: 36px;
  font-size: 13px;
  transition: all 0.2s ease;
}

:deep(.el-menu-item:hover) {
  background: #f8fafc !important;
  color: #2563eb !important;
}

/* 响应式优化 */
@media (max-width: 768px) {
  .header-content {
    height: auto;
    flex-direction: column;
    align-items: flex-start;
    margin: 12px;
  }

  .welcome-section {
    width: 100%;
    justify-content: space-between;
    padding: 8px 0;
  }

  .user-menu {
    width: 100%;
    margin-top: 8px;
    backdrop-filter: none;
  }
}

/* 新增加载过渡效果 */
.header-container {
  opacity: 0;
  transform: translateY(-10px);
  animation: headerEnter 0.4s ease forwards;
}

@keyframes headerEnter {
  to {
    opacity: 1;
    transform: translateY(0);
  }
}
</style>
